<?php

App::uses('AppController', 'Controller');

class OffersController extends AppController {
    
    public $pageTitle = "Ponude";
    
    public $paginate = array(
        'limit' => ITEMS_PER_PAGE
    );
    
    public $uses = array( 'Offer', 'Settings' );

    public function index() {
        $filter = $this->parseFilterData('Offer');
        
        $this->order = "{$filter->sortBy} {$filter->sortDir}";
        $offers = $this->paginate('Offer', $filter->conditions);
        
        $this->set('offers', $offers);
        $this->setFilterData($filter);
    }
    
    private function _setCommonData() {
        $this->set('locations', $this->Offer->Location->find('list'));
        $this->set('clients', $this->Offer->Client->find('list'));
    }
    
    public function create() {
        $this->_setCommonData();
        $this->set('data', $this->Offer->create());
        $this->render('form');
    }
    
    public function edit($id) {
        $this->_setCommonData();
        $this->set('data', $this->Offer->findById($id));
        $this->render('form');
    }
    
    public function save() {
        $data = $this->data;
        if (! empty($data)) {
            $this->Offer->create($data);
            
            if (! $this->Offer->validates()) {
                $this->_setCommonData();
                $this->set('data', $data);
                $this->setFlash('Uneti podaci nisu validni.');
                return $this->render('form');
            }
            
            $this->Offer->cleanRelationsData();
            if (! $this->Offer->saveAll($data)) {
                $this->_setCommonData();
                $this->set('data', $data);
                $this->setFlash('Čuvanje nije uspelo.');
                return $this->render('form');
            }
            
            $this->setFlash('Ponuda je sačuvana.', 'ok');
            $this->redirect('edit/'.$this->Offer->id);
        }
        
        $this->redirect('index');
    }
    
    public function remove($id) {
        if ($this->Offer->delete($id)) {
            $this->setFlash('Ponuda je obrisana.', 'ok');
        } else {
            $this->setFlash('Ponuda nije obrisana.');
        }
        
        $this->redirect('index');
    }
    
    public function pdf($id) {
        $this->set('data', $this->Offer->find('first', array(
            'conditions' => array( 'Offer.id' => $id),
            'recursive'  => 2
        )));
        $this->set('settings', $this->Settings->load());
        
        $this->layout = 'blank';
    }
}
